<template>
  <div class="app-container">
    <div class="filter-container" style="margin-bottom:20px;float:right">
      <el-button type="primary" @click="handleCreate">新增主题</el-button>
    </div>
    <el-table :data="list" v-loading.body="listLoading" element-loading-text="Loading" border fit highlight-current-row>
      <el-table-column align="center" label='主题名称' width="110">
        <template slot-scope="scope">
          {{scope.row.topicName}}
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="图标" width="240" align="center">
        <template slot-scope="scope">
          <div class="row-div-ctx" v-if="scope.row.icon != ''">
            <img :src="scope.row.icon" class="row-div-ctx-img"/>
          </div>
          <span v-else>--</span>
        </template>
      </el-table-column>
      <el-table-column label="年级" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.grades.length == 0">--</span>
          <span v-else v-for="(item, index) in scope.row.grades" :key="index">{{  item.gradeName }} </span>
        </template>
      </el-table-column>
      <el-table-column label="是否有科目" width="110" align="center">
        <template slot-scope="scope">
          <span>{{scope.row.isSubject | statusFilter}}</span>
        </template>
      </el-table-column>
      <el-table-column label="当前序号" width="110" align="center">
        <template slot-scope="scope">
          {{scope.row.sort}}
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="240">
        <template slot-scope="scope">
          <el-button size="small" type="primary" v-if="scope.row.putaway == 0" @click="handleOprate(scope.row,1)">下架</el-button>
          <el-button size="small" type="primary" v-else @click="handleOprate(scope.row,0)">上架</el-button>
          <el-button size="small" @click="handleUpdate(scope.row)">编辑
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :title="dialogStatus=='create' ? '新增主题' : '编辑主题'" :visible.sync="dialogFormVisible" center>
      <el-form :model="form" :rules="rules" ref="ruleForm">
        <el-form-item label="主题名称" label-width="110px" prop="topicName">
          <el-input v-model="form.topicName" auto-complete="off" maxlength="5"
          placeholder="请输入主题名称（不超过5个字）"></el-input>
        </el-form-item>
        <el-form-item label-width="110px" label="图标" class="postInfo-container-item" prop="icon">
            <el-input v-model="form.icon" type='text' style='display:none'></el-input>
            <el-upload
            ref="upload"
            :headers="headers"
            action="/tools/oss/upload"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-success="handleUploadSuccess"
            :file-list="fileList"
            list-type="picture"
            :accept="'.png,.jpg,.jpeg,.gif'"
            :limit="2">
            <el-button size="small" type="primary" icon="el-icon-upload2">点击此处上传图片</el-button>
            <div slot="tip" class="el-upload__tip">注：建议尺寸：96X96px</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="排序" label-width="110px" prop="sort">
          <el-input-number  v-model="form.sort" :step="1" :min="0"></el-input-number>
        </el-form-item>
        <el-form-item label="选择年级" label-width="110px">
          <template slot-scope="scope">
            <el-checkbox-group v-model="gradeIds">
              <el-checkbox class="checkbox-item" :label="item.id" v-for="(item, index) in grades" :key='index' @change="handleChange(item)" :checked="item.selected === 1">{{ item.gradeName }}</el-checkbox>
            </el-checkbox-group>
          </template> 
        </el-form-item>
        <el-form-item label="是否有科目" label-width="110px">
          <el-radio v-model="isSubject" :label="false">否</el-radio>
          <el-radio v-model="isSubject" :label="true">是</el-radio>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="addForm">确 定</el-button>
        <el-button v-else type="primary" @click="updateForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getList, add, update, getId, toggleId } from '@/api/course'
import { getGradeList } from '@/api/grade'
import { getToken } from '@/utils/auth'

export default {
  data() {
    return {
      fileList:[],
      headers:{},
      isSubject:false,
      grades:[],
      gradeIds:[],
      dialogStatus:'create',
      form:{
        id:0,
        icon:'',
        topicName:'',
        gradeIds:'',
        sort:1
      },
      dialogFormVisible:false,
      list: null,
      listLoading: true,
      rules: {
        topicName: [{ required: true, message: '请输入主题名称', trigger: 'blur' }],
        sort: [{ required: true, message: '请输入排序权重', trigger: 'blur' }],
        icon: [{ required: true, message: '请上传图标', trigger: 'change' }]
      }
    }
  },
  mounted() {
    this.headers = { accessToken:getToken() }
    this.fetchData()
    this.fetchGradeData()
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        false:'否',
        true:'是'
      }
      return statusMap[status]
    }
  },
  methods: {
    handleUploadSuccess(rst, file, fileList){
      const { code, data:{ picUrlList } } = rst
      const { form } = this
      if(code == 0){
        this.form.icon = picUrlList[0]
        this.fileList = [{ name:file.url, url:file.url }]
      }else{
        this.$refs.upload.clearFiles()
        this.$notify({
          title: '失败',
          message: message,
          type: 'error',
          duration: 3000
        })
      }
    },
    handlePreview(file) {
    },
    handleRemove(file, fileList) {
      if(fileList.length == 0){
        this.form.icon = ''
        this.$refs.upload.clearFiles()
      }
    },
    handleChange(row){
      row['selected'] = !row['selected']
    },
    handleUpdate(row){
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      getId({ id:row.id }).then(response => {
        const { code, message, data } = response
        const { grades, icon, isSubject } = data
        if(code == 0){
          const arr = []
          const { from } = this
          grades.map(e => {
            if(e.selected == 1){
              arr.push(e.id)
            }
          })
          if(icon.length != 0){
            this.fileList = [{ name:icon, url:icon }]
          }else{
            this.fileList = []
          }
          this.isSubject = isSubject
          this.gradeIds = arr
          this.form = data
        }else{
          this.$message(message)
        }
      })
    },
    handleCreate() {
      this.gradeIds = []
      this.form = {
        id:0,
        icon:'',
        topicName:'',
        gradeIds:'',
        sort:1
      }
      this.isSubject = false
      this.fileList = []
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    updateForm(){
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          const { form, gradeIds } = this
          form['gradeIds'] = gradeIds
          form['isSubject'] = this.isSubject
          update(form).then(response => {
            const { code, message } = response
            if(code == 0){
              this.fetchData()
              this.dialogFormVisible = false
            }else{
              this.$message(message)
            }
          })
        } else {
          return false
        }
      })
    },
    addForm() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          const { form, gradeIds } = this
          form['gradeIds'] = gradeIds
          form['isSubject'] = this.isSubject
          add(form).then(response => {
            const { code, message } = response
            if(code == 0){
              this.fetchData()
              this.dialogFormVisible = false
            }else{
              this.$message(message)
            }
          })
        } else {
          return false
        }
      })
    },
    fetchGradeData() {
      getGradeList().then(response => {
        this.grades = response.data
      })
    },
    handleOprate(row, type){
      this.$confirm(`你确定要将此主题“${row.topicName}”${type == 1 ? '下架' : '上架'}？`)
        .then(() => {
          toggleId({ id:row.id, operateType:type }).then(res => {
            const { code } = res
            if(code == 0){
              this.$notify({
                message: `${type == 1 ? '下架' : '上架'}成功`,
                type: 'success',
                duration: 2000
              })
              row['putaway'] = type
            }else{
              this.$notify({
                message: res.message,
                type: 'error',
                duration: 2000
              })
            }
          })
        })
        .catch(() => {})
    },
    fetchData() {
      this.listLoading = true
      getList().then(response => {
        this.list = response.data
        this.listLoading = false
      })
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.row-div-ctx{
  width:48px;
  height:48px;
  overflow:hidden;
  border-radius:48px;
  margin: 0 auto;
}
.row-div-ctx-img{
  height:48px;
}
.pagination-container{
  margin-top:30px;
}
.checkbox-item{
    margin-right:30px;
    margin-left:0;
  }
</style>
